package org.road0329.dlt698.axdr;

import org.road0329.dlt698.ReverseByteArrayInputStream;
import org.road0329.dlt698.ReverseByteArrayOutputStream;
import org.road0329.dlt698.asn1.axdr.AxdrBoolean;
import org.road0329.dlt698.asn1.axdr.AxdrType;

import java.io.IOException;

public class GetResponseNext extends AxdrType {
    private byte[] dataCode;
    private PIID piid_acd;
    private AxdrBoolean lastFrameFlag;
    private Unsigned16 frameNo;
    private SubChoiceFrameResp frameResp;

    public GetResponseNext() {
    }

    public void set_dataCode(byte[] dataCode) {
        this.dataCode = dataCode;
    }

    public void set_all(PIID piid_acd, AxdrBoolean lastFrameFlag, Unsigned16 frameNo, SubChoiceFrameResp frameResp) {
        this.piid_acd = piid_acd;
        this.lastFrameFlag = lastFrameFlag;
        this.frameNo = frameNo;
        this.frameResp = frameResp;
    }

    public int decode(ReverseByteArrayInputStream input) throws Exception {
        int codeLength = 0;
        piid_acd = new PIID();
        piid_acd.setNumBit(8);
        codeLength += piid_acd.decode(input);
        lastFrameFlag = new AxdrBoolean();
        codeLength += lastFrameFlag.decode(input);
        frameNo = new Unsigned16();
        frameNo.setConst();
        codeLength += frameNo.decode(input);
        frameResp = new SubChoiceFrameResp();
        codeLength += frameResp.decode(input);
        return codeLength;
    }

    public int encode(ReverseByteArrayOutputStream output) throws Exception {
        int codeLength;
        if (dataCode != null) {
            codeLength = dataCode.length;
            for (int i = dataCode.length - 1; i >= 0; i--) {
                output.write(dataCode[i]);
            }
        } else {
            if (frameResp != null && frameNo != null && lastFrameFlag != null && piid_acd != null) {
                codeLength = 0;
                codeLength += frameResp.encode(output);
                codeLength += frameNo.encode(output);
                codeLength += lastFrameFlag.encode(output);
                codeLength += piid_acd.encode(output);
            } else {
                throw new Exception("piid_acd || frameResp || lastFrameFlag || frameNo is null");
            }
        }
        return codeLength;
    }

    public void encodeAndSave(int encodingSizeGuess) throws Exception {
        ReverseByteArrayOutputStream revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        encode(revOStream);
        dataCode = revOStream.getArray();
    }

    public String toString() {
        if (piid_acd != null && lastFrameFlag != null && frameNo != null && frameResp != null) {
            return "sequence: {" + "piid_acd: " + piid_acd + ", lastframeflag: " + lastFrameFlag + ", frameno: "
                    + frameNo + ", frameresp: " + frameResp + "}";
        } else {
            return "piid_acd || frameResp || lastFrameFlag || frameNo is null";
        }
    }
}
